package cn.iocoder.yudao.module.system.util.baidu;

import cn.iocoder.yudao.module.system.controller.admin.ai.vo.UserReportSaveReqVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.Calendar;
import java.util.StringJoiner;
import org.apache.commons.lang3.StringUtils;

public class TextFomatterUtils {

    //体验版沟通指令文本：无意向专业、学校，无未来规划的文本。
    public static final String SD_DEFAULT_TEXT = "{province}{year}年考生，{gender}，高考总分{scores}，选科是{majors}。";
    //体验版通指令文本：无意向学校，无未来规划的文本。
    public static final String SD_DEFAULT_TEXT_1 = "{province}{year}年考生，{gender}，高考总分{scores}，选科是{majors},对{interestedMajor}感兴趣。";
    //体验版沟通指令文本：无意向学校。
    public static final String SD_DEFAULT_TEXT_2 = "{province}{year}年考生，{gender}，高考总分{scores}，选科是{majors},对{interestedMajor}感兴趣，我大学毕业后会{planning}。";

    //专业版沟通指令文本：无意向专业、学校，无未来规划的文本。
    private static final String PR_DEFAULT_TEXT = "{province}{year}年考生，{gender}，高考总分:{scores}{scores1}。考生性格{nature}，学习能力{learnAbility}，社交能力{socialSkills}，家庭年收入{salary}。未来就业希望在{employmentIntentions}人脉资源有：{Connections},想去的学校所在地：{schoolAddress}。";

    private static final String PR_DEFAULT_TEXT_1 = "{province}{year}年考生，{gender}，选科是{majors}，高考总分{scores}其中{scores1}。考生性格{nature}，学习能力{learnAbility}，社交能力{socialSkills}，家庭年收入{salary}。未来就业希望在{employmentIntentions},人脉资源有:{Connections},对{interestedMajor}感兴趣,想去的学校所在地：{schoolAddress}。";
    private static final String PR_DEFAULT_TEXT_2 = "{province}{year}年考生，{gender}，选科是{majors}，高考总分{scores}其中{scores1}。考生性格{nature}，学习能力{learnAbility}，社交能力{socialSkills}，家庭年收入{salary}，大学毕业后会{planning}。未来就业希望在{employmentIntentions}，人脉资源有:{Connections},对{interestedMajor}感兴趣,想去的学校所在地：{schoolAddress}。";

    /**
     * 将问卷JSON字符串转换为模板文本
     * 
     * @param jsonStr 问卷JSON字符串
     * @param version 版本号：1-体验版，2-专业版
     * @return 根据条件返回对应的模板文本
     */
    public static String convertQuestionnaireToTemplateTexts(String jsonStr, Integer version) {
        try {
            // 解析JSON字符串
            JSONObject questionObj = JSON.parseObject(jsonStr);
            
            // 获取当前年份
            int currentYear = Calendar.getInstance().get(Calendar.YEAR);
            
            // 提取问卷信息
            String province = getQuestionAnswer(questionObj, "1", "questionContent", "学生所处的高考省份");
            String gender = getQuestionAnswer(questionObj, "2", "questionContent", "学生性别");
            String scores = getQuestionAnswer(questionObj, "5", "questionContent", "高考总分");
            String scores1 = getQuestionAnswer(questionObj, "6", "questionContent", "各科分数");
            String planning = getQuestionAnswer(questionObj, "14", "questionContent", "毕业去向");
            String learnAbility = getQuestionAnswer(questionObj, "9", "questionContent", "学习能力");
            String socialSkills = getQuestionAnswer(questionObj, "10", "questionContent", "社交能力");
            String salary = getQuestionAnswer(questionObj, "11", "questionContent", "家庭年收入（单位元）");
            String employmentIntentions = getQuestionAnswer(questionObj, "12", "questionContent", "就业方向");
            String connections = getQuestionAnswer(questionObj, "13", "questionContent", "人脉资源");
            String nature = getQuestionAnswer(questionObj, "8", "questionContent", "性格");
            String schoolAddress = getQuestionAnswer(questionObj, "15", "questionContent", "就读城市省份");

            // 提取最高分和最低分
            String maxScore = getQuestionAnswer(questionObj, "maxScore", "questionContent", "最高分");
            String minScore = getQuestionAnswer(questionObj, "minScore", "questionContent", "最低分");

            // 获取选科信息
            String majors = "";
            if (questionObj.containsKey("3") && questionObj.getJSONObject("3").getString("questionContent").equals("学生选科")) {
                JSONArray majorsArray = questionObj.getJSONObject("3").getJSONArray("answer");
                if (majorsArray != null && !majorsArray.isEmpty()) {
                    StringJoiner joiner = new StringJoiner("、");
                    for (int i = 0; i < majorsArray.size(); i++) {
                        joiner.add(majorsArray.getString(i));
                    }
                    majors = joiner.toString();
                }
            }
            
            // 获取意向专业
            String interestedMajors = "";
            if (questionObj.containsKey("7") && questionObj.getJSONObject("7").getString("questionContent").equals("意向专业")) {
                JSONArray interestedArray = questionObj.getJSONObject("7").getJSONArray("answer");
                if (interestedArray != null && !interestedArray.isEmpty()) {
                    StringJoiner joiner = new StringJoiner("、");
                    for (int i = 0; i < interestedArray.size(); i++) {
                        joiner.add(interestedArray.getString(i));
                    }
                    interestedMajors = joiner.toString();
                }
            }
            
            // 判断是否有意向专业和未来规划
            boolean hasInterestedMajors = StringUtils.isNotBlank(interestedMajors);
            boolean hasPlanning = StringUtils.isNotBlank(planning);

            // 格式化分数信息，包含分数范围
            String formattedScores = formatScoresWithRange(scores, minScore, maxScore);
            
            // 根据版本和条件选择不同的模板
            String resultText;

            if (2==version) {
                // 专业版模板
                if (!hasInterestedMajors && !hasPlanning) {
                    // 无意向专业、学校，无未来规划的文本
                    resultText = PR_DEFAULT_TEXT
                            .replace("{province}", province)
                            .replace("{year}", String.valueOf(currentYear))
                            .replace("{gender}", gender)
                            .replace("{scores}", formattedScores)
                            .replace("{scores1}", scores1)
                            .replace("{majors}", majors)
                            // 以下是专业版特有的占位符，暂时用空字符串替代
                            .replace("{nature}", nature)
                            .replace("{learnAbility}", learnAbility)
                            .replace("{socialSkills}", socialSkills)
                            .replace("{salary}", salary)
                            .replace("{employmentIntentions}", employmentIntentions)
                            .replace("{Connections}", connections)
                            .replace("{schoolAddress}", schoolAddress)
                    ;
                } else if (hasInterestedMajors && !hasPlanning) {
                    // 无意向学校，无未来规划的文本
                    resultText = PR_DEFAULT_TEXT_1
                            .replace("{province}", province)
                            .replace("{year}", String.valueOf(currentYear))
                            .replace("{gender}", gender)
                            .replace("{scores}", formattedScores)
                            .replace("{scores1}", scores1)
                            .replace("{majors}", majors)
                            .replace("{interestedMajor}", interestedMajors)
                            // 以下是专业版特有的占位符，暂时用空字符串替代
                            .replace("{nature}", "")
                            .replace("{learnAbility}", learnAbility)
                            .replace("{socialSkills}", socialSkills)
                            .replace("{salary}", salary)
                            .replace("{employmentIntentions}", employmentIntentions)
                            .replace("{Connections}", connections)
                            .replace("{schoolAddress}", schoolAddress)
                    ;
                } else {
                    // 无意向学校
                    resultText = PR_DEFAULT_TEXT_2
                            .replace("{province}", province)
                            .replace("{year}", String.valueOf(currentYear))
                            .replace("{gender}", gender)
                            .replace("{scores}", formattedScores)
                            .replace("{scores1}", scores1)
                            .replace("{majors}", majors)
                            .replace("{interestedMajor}", hasInterestedMajors ? interestedMajors : "无意向专业")
                            .replace("{planning}", planning)
                            // 以下是专业版特有的占位符，暂时用空字符串替代
                            .replace("{nature}", nature)
                            .replace("{learnAbility}", learnAbility)
                            .replace("{socialSkills}", socialSkills)
                            .replace("{salary}", salary)
                            .replace("{employmentIntentions}", employmentIntentions)
                            .replace("{Connections}", connections)
                            .replace("{schoolAddress}", schoolAddress)
                   ;
                }
            } else {
                // 体验版模板 (默认为版本1)
                if (!hasInterestedMajors && !hasPlanning) {
                    // 无意向专业、学校，无未来规划的文本
                    resultText = SD_DEFAULT_TEXT
                            .replace("{province}", province)
                            .replace("{year}", String.valueOf(currentYear))
                            .replace("{gender}", gender)
                            .replace("{scores}", formattedScores)
                            .replace("{majors}", majors);
                } else if (hasInterestedMajors && !hasPlanning) {
                    // 无意向学校，无未来规划的文本
                    resultText = SD_DEFAULT_TEXT_1
                            .replace("{province}", province)
                            .replace("{year}", String.valueOf(currentYear))
                            .replace("{gender}", gender)
                            .replace("{scores}", formattedScores)
                            .replace("{majors}", majors)
                            .replace("{interestedMajor}", interestedMajors);
                } else {
                    // 无意向学校
                    resultText = SD_DEFAULT_TEXT_2
                            .replace("{province}", province)
                            .replace("{year}", String.valueOf(currentYear))
                            .replace("{gender}", gender)
                            .replace("{scores}", formattedScores)
                            .replace("{majors}", majors)
                            .replace("{interestedMajor}", hasInterestedMajors ? interestedMajors : "无意向专业")
                            .replace("{planning}", planning);
                }
            }

            return resultText;
        } catch (Exception e) {
            // 发生异常时返回空字符串
            return "";
        }
    }
    
    /**
     * 将问卷JSON字符串转换为模板文本（默认使用体验版）
     * 
     * @param jsonStr 问卷JSON字符串
     * @return 根据条件返回对应的模板文本
     */
    public static String convertQuestionnaireToTemplateTexts(String jsonStr) {
        return convertQuestionnaireToTemplateTexts(jsonStr, 1);
    }
    
    /**
     * 格式化分数信息，包含分数范围
     *
     * @param scores 高考总分
     * @param minScore 最低分
     * @param maxScore 最高分
     * @return 格式化后的分数信息
     */
    private static String formatScoresWithRange(String scores, String minScore, String maxScore) {
        if (StringUtils.isBlank(scores)) {
            return "";
        }

        StringBuilder formattedScores = new StringBuilder(scores);

        // 如果有最低分和最高分，添加分数范围信息
        if (StringUtils.isNotBlank(minScore) && StringUtils.isNotBlank(maxScore)) {
            formattedScores.append("（分数范围：").append(minScore).append("-").append(maxScore).append("）");
        } else if (StringUtils.isNotBlank(minScore)) {
            formattedScores.append("（最低分：").append(minScore).append("）");
        } else if (StringUtils.isNotBlank(maxScore)) {
            formattedScores.append("（最高分：").append(maxScore).append("）");
        }

        return formattedScores.toString();
    }

    /**
     * 从问卷对象中获取指定问题的答案
     *
     * @param questionObj 问卷JSON对象
     * @param questionId 问题ID
     * @param contentKey 问题内容的键名
     * @param expectedContent 预期的问题内容
     * @return 问题的答案，如果问题不存在或内容不匹配则返回空字符串
     */
    private static String getQuestionAnswer(JSONObject questionObj, String questionId, String contentKey, String expectedContent) {
        if (questionObj.containsKey(questionId)) {
            JSONObject question = questionObj.getJSONObject(questionId);
            if (question.getString(contentKey).equals(expectedContent)) {
                return question.containsKey("answer") ? question.getString("answer") : "";
            }
        }
        return "";
    }
    
    /**
     * 测试方法
     */
    public static void main(String[] args) {
        // 测试JSON字符串，包含maxScore和minScore
        String testJson = "{\"1\":{\"questionContent\":\"学生所处的高考省份\",\"answer\":\"山东\"},\"2\":{\"questionContent\":\"学生性别\",\"answer\":\"我是女生\"},\"3\":{\"questionContent\":\"学生选科\",\"answer\":[\"物理\",\"化学\",\"生物\"]},\"5\":{\"questionContent\":\"高考总分\",\"answer\":\"542\"},\"6\":{\"questionContent\":\"各科分数\",\"answer\":\"语文:111,数学:111,英语:111,物理:99,化学:99,生物:11\"},\"7\":{\"questionContent\":\"意向专业\",\"answer\":[\"地质学\"]},\"8\":{\"questionContent\":\"性格\",\"answer\":\"外向\"},\"9\":{\"questionContent\":\"学习能力\",\"answer\":\"强\"},\"10\":{\"questionContent\":\"社交能力\",\"answer\":\"弱\"},\"11\":{\"questionContent\":\"家庭年收入（单位元）\",\"answer\":\"10万到20万\"},\"12\":{\"questionContent\":\"就业方向\",\"answer\":\"体制内\"},\"14\":{\"questionContent\":\"毕业去向\",\"answer\":\"考研\"},\"15\":{\"questionContent\":\"就读城市省份\",\"answer\":\"全国\"},\"maxScore\":{\"questionContent\":\"最高分\",\"answer\":\"547\"},\"minScore\":{\"questionContent\":\"最低分\",\"answer\":\"537\"}}";

        // 测试体验版
        System.out.println("=== 体验版 ===");
        String result1 = convertQuestionnaireToTemplateTexts(testJson, 1);
        System.out.println(result1);

        // 测试专业版
        System.out.println("\n=== 专业版 ===");
        String result2 = convertQuestionnaireToTemplateTexts(testJson, 2);
        System.out.println(result2);
    }
}
